#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FileSecurityScanningTool
版本: 1.0
作者: SamWu
邮箱: samwulqy@gmail.com
日期: 2025年9月28日
描述: 一款高性能本地安全扫描工具
"""

import os
import hashlib
import pefile
import zipfile
import json
import re
import sqlite3
import logging
import mmap
import time
import platform
import subprocess
import tempfile
import lief
import binascii
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("secure_scan.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("SecureScanPro")

class SecureScanPro:
    def __init__(self):
        self.version = "1.0"
        self.author = "SamWu"
        self.email = "samwulqy@gmail.com"
        self.release_date = "2025-09-28"
        
        # 初始化配置
        self.max_file_size = 500 * 1024 * 1024  # 500MB
        self.scan_timeout = 60.0  # 60秒超时
        self.heuristic_threshold = 0.7  # 启发式检测阈值
        self.thread_pool = ThreadPoolExecutor(max_workers=4)
        
        # 初始化数据库
        self.scan_history_db = "secure_scan_pro.db"
        self._init_database()
        
        # 加载安全资源
        self.malware_signatures = self._load_malware_signatures()
        self.crack_keywords = self._load_crack_keywords()
        self.trusted_certificates = self._load_trusted_certificates()
        self.whitelist_hashes = self._load_whitelist_hashes()
        self.suspicious_patterns = self._load_suspicious_patterns()
        self.file_type_signatures = self._load_file_type_signatures()
        
        logger.info(f"SecureScan Pro v{self.version} 初始化完成 - {self.author}")

    def _init_database(self):
        """初始化扫描历史数据库"""
        conn = sqlite3.connect(self.scan_history_db)
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS scan_history
                     (id INTEGER PRIMARY KEY AUTOINCREMENT,
                      file_path TEXT,
                      file_hash TEXT,
                      file_size INTEGER,
                      file_type TEXT,
                      scan_time DATETIME,
                      is_malware BOOLEAN,
                      is_tampered BOOLEAN,
                      is_crack BOOLEAN,
                      risk_score REAL,
                      details TEXT)''')
        c.execute('''CREATE TABLE IF NOT EXISTS malware_signatures
                     (signature TEXT PRIMARY KEY,
                      description TEXT,
                      added_date DATETIME)''')
        conn.commit()
        conn.close()

    def _load_malware_signatures(self):
        """加载恶意软件特征库"""
        signatures = {}
        try:
            conn = sqlite3.connect(self.scan_history_db)
            c = conn.cursor()
            c.execute("SELECT signature, description FROM malware_signatures")
            for row in c.fetchall():
                signatures[row[0]] = row[1]
            conn.close()
        except:
            pass
        
        # 添加默认签名
        if not signatures:
            signatures.update({
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855": "空文件",
                "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3": "测试恶意软件签名",
                "7d97e98c8af7c4d4b0b1ad9b3c6d3a8e": "示例勒索软件签名",
                "6f4b4b5a76a5a5a5a5a5a5a5a5a5a5a5": "示例后门程序签名"
            })
        
        logger.info(f"加载 {len(signatures)} 个恶意软件签名")
        return signatures

    def _load_crack_keywords(self):
        """加载破解软件关键词"""
        keywords = [
            "crack", "keygen", "serial", "patch", "license", "activator", 
            "torrent", "注册机", "破解", "激活", "注册码", "免安装",
            "preactivated", "keymaker", "loader", "kegen", "cracked",
            "genuine", "full version", "nulled", "warez", "patch"
        ]
        logger.info(f"加载 {len(keywords)} 个破解软件关键词")
        return keywords

    def _load_trusted_certificates(self):
        """加载可信证书列表"""
        trusted = [
            "Microsoft", "Adobe", "Google", "Mozilla", "Oracle", "Miaostars",
            "Apple", "Canonical", "JetBrains", "Intel", "AMD",
            "NVIDIA", "Dell", "HP", "Lenovo", "Samsung"
        ]
        logger.info(f"加载 {len(trusted)} 个可信证书发布者")
        return trusted

    def _load_whitelist_hashes(self):
        """加载白名单文件哈希"""
        whitelist = {
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855": "空文件",
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824": "hello"
        }
        logger.info(f"加载 {len(whitelist)} 个白名单哈希")
        return whitelist

    def _load_suspicious_patterns(self):
        """加载可疑字节模式"""
        patterns = [
            b'\xE8\x00\x00\x00\x00',  # 远跳转指令
            b'\x0F\x01\xD0',          # 可疑系统调用
            b'\xCD\x80',              # Linux系统调用
            b'\xCD\x21',              # DOS系统调用
            b'\x0F\x34',              # sysenter指令
            b'\x0F\x05',              # syscall指令
            b'\xEB\x02',              # 短跳转
            b'\x90\x90\x90',          # NOP雪橇
            b'\x68\x65\x6C\x6C\x6F',  # "hello"字符串
            b'\x4D\x5A',              # MZ头 (可执行文件)
            b'\x7F\x45\x4C\x46',      # ELF头
            b'\x23\x21',              # Shebang (#!)
            b'\xEF\xBB\xBF',          # UTF-8 BOM
            b'\xFF\xFE',              # UTF-16 LE BOM
            b'\xFE\xFF',              # UTF-16 BE BOM
            b'\x50\x4B\x03\x04',      # ZIP文件头
            b'\x52\x61\x72\x21',      # RAR文件头
        ]
        logger.info(f"加载 {len(patterns)} 个可疑字节模式")
        return patterns

    def _load_file_type_signatures(self):
        """加载文件类型签名"""
        signatures = {
            b'\xFF\xD8\xFF': 'JPEG',
            b'\x89\x50\x4E\x47': 'PNG',
            b'\x47\x49\x46\x38': 'GIF',
            b'\x25\x50\x44\x46': 'PDF',
            b'\x50\x4B\x03\x04': 'ZIP',
            b'\x52\x61\x72\x21': 'RAR',
            b'\x7F\x45\x4C\x46': 'ELF',
            b'\x4D\x5A': 'EXE',
            b'\x23\x21': 'SCRIPT',
            b'\xEF\xBB\xBF': 'UTF8',
            b'\xFF\xFE': 'UTF16',
            b'\xFE\xFF': 'UTF16BE',
            b'\x49\x44\x33': 'MP3',
            b'\x00\x00\x00\x20\x66\x74\x79\x70': 'MP4',
            b'\x52\x49\x46\x46': 'AVI/WAV',
        }
        logger.info(f"加载 {len(signatures)} 个文件类型签名")
        return signatures

    def scan_file(self, file_path: str) -> dict:
        """
        执行安全扫描 - 保证1秒内完成
        :param file_path: 要扫描的文件路径
        :return: 包含扫描结果的字典
        """
        start_time = time.time()
        
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件不存在: {file_path}")
        
        # 初始化结果对象
        results = {
            'file_path': file_path,
            'file_size': os.path.getsize(file_path),
            'file_type': 'unknown',
            'file_hash': '',
            'is_malware': False,
            'is_tampered': False,
            'is_crack': False,
            'risk_score': 0.0,
            'warnings': [],
            'signature_match': None,
            'certificate_info': None,
            'pe_analysis': None,
            'heuristic_analysis': None,
            'scan_time': datetime.now().isoformat(),
            'scan_duration': 0.0
        }
        
        # 1. 快速文件类型检测
        results['file_type'] = self._detect_file_type(file_path)
        
        # 2. 计算文件哈希 (使用快速方法)
        results['file_hash'] = self._fast_file_hash(file_path)
        
        # 3. 检查白名单
        if results['file_hash'] in self.whitelist_hashes:
            results['risk_score'] = 0.0
            results['scan_duration'] = time.time() - start_time
            self._save_scan_result(results)
            return results
        
        # 4. 并行执行检测任务
        futures = {
            'malware': self.thread_pool.submit(self._check_malware_signature, results['file_hash']),
            'crack': self.thread_pool.submit(self._detect_crack_package, file_path),
            'tamper': self.thread_pool.submit(self._check_file_tampering, file_path),
            'heuristic': self.thread_pool.submit(self._heuristic_analysis, file_path),
            'pe_analysis': self.thread_pool.submit(self._analyze_pe_file, file_path) if results['file_type'] == 'executable' else None,
            'certificate': self.thread_pool.submit(self._verify_signature, file_path) if platform.system() == 'Windows' else None
        }
        
        # 5. 收集结果 (带超时)
        timeout = self.scan_timeout - (time.time() - start_time)
        if timeout < 0.1:
            timeout = 0.1
            
        for key, future in futures.items():
            if future:
                try:
                    result = future.result(timeout=timeout)
                    if key == 'malware' and result:
                        results['is_malware'] = True
                        results['signature_match'] = result
                        results['risk_score'] = max(results['risk_score'], 1.0)
                        results['warnings'].append(f"检测到已知恶意软件签名: {result}")
                    elif key == 'crack' and result:
                        results['is_crack'] = True
                        results['risk_score'] = max(results['risk_score'], 0.8)
                        results['warnings'].append("检测到潜在破解软件特征")
                    elif key == 'tamper' and result:
                        results['is_tampered'] = True
                        results['risk_score'] = max(results['risk_score'], 0.7)
                        results['warnings'].append("文件可能已被篡改")
                    elif key == 'heuristic':
                        results['heuristic_analysis'] = result
                        if result > self.heuristic_threshold:
                            results['risk_score'] = max(results['risk_score'], result)
                            results['warnings'].append(f"启发式分析发现高风险特征 (分数: {result:.2f})")
                    elif key == 'pe_analysis':
                        results['pe_analysis'] = result
                        if result and result.get('suspicious', False):
                            results['risk_score'] = max(results['risk_score'], result.get('risk_score', 0.0))
                            results['warnings'].append("PE文件分析发现可疑特征")
                    elif key == 'certificate':
                        results['certificate_info'] = result
                        if result and not result.get('signed', False):
                            results['risk_score'] = min(1.0, results['risk_score'] + 0.2)
                            results['warnings'].append("文件未经过数字签名")
                        elif result and not result.get('trusted', False):
                            results['risk_score'] = min(1.0, results['risk_score'] + 0.1)
                            results['warnings'].append("文件签名来自不受信任的证书")
                except Exception as e:
                    logger.warning(f"{key} 检测超时或失败: {str(e)}")
        
        # 6. 保存并返回结果
        results['scan_duration'] = time.time() - start_time
        self._save_scan_result(results)
        return results

    def _save_scan_result(self, results: dict) -> dict:
        """保存扫描结果到数据库"""
        try:
            conn = sqlite3.connect(self.scan_history_db)
            c = conn.cursor()
            c.execute('''INSERT INTO scan_history 
                         (file_path, file_hash, file_size, file_type, scan_time, 
                         is_malware, is_tampered, is_crack, risk_score, details)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                     (results['file_path'], 
                      results['file_hash'],
                      results['file_size'],
                      results['file_type'],
                      results['scan_time'],
                      results['is_malware'],
                      results['is_tampered'],
                      results['is_crack'],
                      results['risk_score'],
                      json.dumps(results)))
            conn.commit()
            conn.close()
        except Exception as e:
            logger.error(f"保存扫描结果失败: {str(e)}")
        return results

    def _detect_file_type(self, file_path: str) -> str:
        """快速检测文件类型"""
        try:
            # 检查文件扩展名
            _, ext = os.path.splitext(file_path)
            ext = ext.lower()
            if ext in ['.exe', '.dll', '.sys', '.scr']:
                return "executable"
            elif ext in ['.js', '.vbs', '.ps1', '.bat', '.cmd', '.sh']:
                return "script"
            elif ext in ['.zip', '.rar', '.7z', '.tar', '.gz']:
                return "archive"
            elif ext in ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']:
                return "document"
            elif ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
                return "image"
            elif ext in ['.mp3', '.wav', '.flac']:
                return "audio"
            elif ext in ['.mp4', '.avi', '.mkv', '.mov']:
                return "video"
            
            # 检查文件签名
            with open(file_path, 'rb') as f:
                header = f.read(32)
                for sig, file_type in self.file_type_signatures.items():
                    if header.startswith(sig):
                        if file_type == 'EXE':
                            return "executable"
                        elif file_type == 'SCRIPT':
                            return "script"
                        elif file_type == 'ZIP' or file_type == 'RAR':
                            return "archive"
                        return file_type.lower()
            
            return "unknown"
        except Exception as e:
            logger.error(f"文件类型检测失败: {str(e)}")
            return "unknown"

    def _fast_file_hash(self, file_path: str, algorithm: str = 'sha256') -> str:
        """快速计算文件哈希值 (使用内存映射)"""
        try:
            hash_func = hashlib.sha256()
            file_size = os.path.getsize(file_path)
            
            # 对于大文件，只计算部分哈希
            if file_size > 10 * 1024 * 1024:  # >10MB
                with open(file_path, 'rb') as f:
                    # 读取文件头
                    hash_func.update(f.read(65536))
                    
                    # 读取文件中间部分
                    f.seek(file_size // 2)
                    hash_func.update(f.read(65536))
                    
                    # 读取文件尾部
                    f.seek(-65536, os.SEEK_END)
                    hash_func.update(f.read(65536))
            else:
                with open(file_path, 'rb') as f:
                    for chunk in iter(lambda: f.read(65536), b''):
                        hash_func.update(chunk)
            
            return hash_func.hexdigest()
        except Exception as e:
            logger.error(f"计算文件哈希失败: {str(e)}")
            return ""

    def _check_malware_signature(self, file_hash: str) -> str:
        """检查文件哈希是否匹配已知恶意软件签名"""
        return self.malware_signatures.get(file_hash)

    def _detect_crack_package(self, file_path: str) -> bool:
        """检测是否为破解包"""
        try:
            # 方法1: 检查文件名和路径中的关键词
            filename = os.path.basename(file_path).lower()
            if any(keyword in filename for keyword in self.crack_keywords):
                return True
            
            # 方法2: 检查文件内容中的常见破解关键词
            with open(file_path, 'rb') as f:
                # 只读取前32KB内容进行关键词扫描
                content = f.read(32768).decode('utf-8', errors='ignore').lower()
                if any(keyword in content for keyword in self.crack_keywords):
                    return True
            
            # 方法3: 检查压缩文件内的文件
            if zipfile.is_zipfile(file_path):
                with zipfile.ZipFile(file_path, 'r') as zip_ref:
                    for name in zip_ref.namelist():
                        if any(keyword in name.lower() for keyword in self.crack_keywords):
                            return True
            return False
        except Exception as e:
            logger.error(f"破解包检测失败: {str(e)}")
            return False

    def _check_file_tampering(self, file_path: str) -> bool:
        """检查文件是否被篡改"""
        try:
            # 方法1: 检查文件完整性标记
            if os.path.exists(file_path + '.sig'):
                return not self._verify_signature(file_path).get('valid', False)
            
            # 方法2: 检查PE文件的校验和
            if self._detect_file_type(file_path) == 'executable':
                try:
                    pe = pefile.PE(file_path)
                    if hasattr(pe, 'OPTIONAL_HEADER') and pe.OPTIONAL_HEADER.CheckSum != 0:
                        calculated_checksum = pe.generate_checksum()
                        if pe.OPTIONAL_HEADER.CheckSum != calculated_checksum:
                            return True
                except:
                    pass
            return False
        except Exception as e:
            logger.error(f"文件篡改检测失败: {str(e)}")
            return False

    def _analyze_pe_file(self, file_path: str) -> dict:
        """分析PE文件结构"""
        result = {
            'sections': [],
            'imports': [],
            'exports': [],
            'resources': [],
            'suspicious': False,
            'risk_score': 0.0,
            'warnings': []
        }
        
        try:
            binary = lief.parse(file_path)
            if not binary:
                return result
            
            # 分析节区
            for section in binary.sections:
                section_info = {
                    'name': section.name,
                    'size': section.size,
                    'entropy': section.entropy,
                    'characteristics': section.characteristics
                }
                result['sections'].append(section_info)
                
                # 高熵节区可能是加壳或加密
                if section.entropy > 7.0:
                    result['risk_score'] += 0.2
                    result['warnings'].append(f"高熵节区: {section.name} (熵值: {section.entropy:.2f})")
                    result['suspicious'] = True
            
            # 分析导入函数
            for func in binary.imported_functions:
                result['imports'].append(func.name)
                
                # 检测可疑API调用
                suspicious_apis = ['VirtualAlloc', 'VirtualProtect', 'CreateRemoteThread', 
                                  'WriteProcessMemory', 'LoadLibrary', 'GetProcAddress',
                                  'WinExec', 'ShellExecute', 'RegSetValue', 'CreateService']
                if func.name in suspicious_apis:
                    result['risk_score'] += 0.1
                    result['warnings'].append(f"可疑API导入: {func.name}")
                    result['suspicious'] = True
            
            # 分析导出函数
            for func in binary.exported_functions:
                result['exports'].append(func.name)
            
            # 分析资源
            for resource in binary.resources:
                resource_info = {
                    'type': resource.type,
                    'size': resource.size
                }
                result['resources'].append(resource_info)
            
            # 检测可疑入口点
            if binary.entrypoint and binary.entrypoint > binary.imagebase + binary.sections[0].virtual_address:
                result['risk_score'] += 0.3
                result['warnings'].append(f"可疑入口点: 0x{binary.entrypoint:x}")
                result['suspicious'] = True
            
            # 限制风险分数不超过1.0
            result['risk_score'] = min(1.0, result['risk_score'])
            
            return result
        except Exception as e:
            logger.error(f"PE文件分析失败: {str(e)}")
            return result

    def _heuristic_analysis(self, file_path: str) -> float:
        """启发式分析检测未知威胁"""
        risk_score = 0.0
        
        try:
            # 方法1: 检测可疑字节模式
            with open(file_path, 'rb') as f:
                content = f.read(65536)  # 读取前64KB
                
                for pattern in self.suspicious_patterns:
                    if content.find(pattern) != -1:
                        risk_score += 0.2
                        logger.debug(f"检测到可疑字节模式: {binascii.hexlify(pattern).decode()}")
            
            # 方法2: 检测异常文件结构
            file_type = self._detect_file_type(file_path)
            if file_type == 'executable':
                # 检查是否有多个可执行节区
                try:
                    pe = pefile.PE(file_path)
                    executable_sections = sum(1 for s in pe.sections if s.Characteristics & 0x20000000)
                    if executable_sections > 1:
                        risk_score += 0.3
                except:
                    pass
            
            # 方法3: 检测异常文件扩展名
            filename = os.path.basename(file_path)
            _, ext = os.path.splitext(filename)
            if file_type == 'executable' and ext.lower() not in ['.exe', '.dll', '.sys', '.scr']:
                risk_score += 0.2
            elif file_type == 'script' and ext.lower() not in ['.js', '.vbs', '.ps1', '.bat', '.cmd', '.sh']:
                risk_score += 0.2
            
            return min(1.0, risk_score)
        except Exception as e:
            logger.error(f"启发式分析失败: {str(e)}")
            return 0.0

    def _verify_signature(self, file_path: str) -> dict:
        """验证文件数字签名 (Windows系统)"""
        result = {
            'signed': False,
            'valid': False,
            'trusted': False,
            'subject': None,
            'issuer': None,
            'timestamp': None
        }
        
        if platform.system() != 'Windows':
            return result
        
        try:
            # 使用Windows的signtool验证签名
            with tempfile.TemporaryDirectory() as tmpdir:
                output_file = os.path.join(tmpdir, "output.txt")
                cmd = f'signtool verify /v /pa "{file_path}" > "{output_file}" 2>&1'
                subprocess.run(cmd, shell=True, check=True, timeout=0.5)
                
                with open(output_file, 'r', encoding='utf-16') as f:
                    output = f.read()
                
                # 解析输出
                if "Successfully verified" in output:
                    result['signed'] = True
                    result['valid'] = True
                    
                    # 提取证书信息
                    subject_match = re.search(r'Subject: (.*)', output)
                    issuer_match = re.search(r'Issuer: (.*)', output)
                    timestamp_match = re.search(r'Date: (.*)', output)
                    
                    if subject_match:
                        result['subject'] = subject_match.group(1)
                    if issuer_match:
                        result['issuer'] = issuer_match.group(1)
                    if timestamp_match:
                        result['timestamp'] = timestamp_match.group(1)
                    
                    # 检查证书是否受信任
                    if result['subject'] and any(trusted in result['subject'] for trusted in self.trusted_certificates):
                        result['trusted'] = True
                elif "No signature found" in output:
                    result['signed'] = False
                else:
                    result['signed'] = True
                    result['valid'] = False
        except Exception as e:
            logger.error(f"签名验证失败: {str(e)}")
        
        return result

    def scan_directory(self, directory: str) -> dict:
        """扫描整个目录"""
        results = {}
        start_time = time.time()
        
        for root, _, files in os.walk(directory):
            for file in files:
                file_path = os.path.join(root, file)
                try:
                    results[file_path] = self.scan_file(file_path)
                except Exception as e:
                    logger.error(f"扫描文件失败 {file_path}: {str(e)}")
                    results[file_path] = {'error': str(e)}
        
        total_time = time.time() - start_time
        logger.info(f"扫描完成: {len(results)} 个文件, 耗时 {total_time:.2f} 秒")
        return results

    def add_malware_signature(self, signature: str, description: str):
        """添加恶意软件签名"""
        try:
            conn = sqlite3.connect(self.scan_history_db)
            c = conn.cursor()
            c.execute("INSERT OR REPLACE INTO malware_signatures (signature, description, added_date) VALUES (?, ?, ?)",
                     (signature, description, datetime.now().isoformat()))
            conn.commit()
            conn.close()
            self.malware_signatures[signature] = description
            logger.info(f"添加恶意软件签名: {signature}")
            return True
        except Exception as e:
            logger.error(f"添加恶意软件签名失败: {str(e)}")
            return False

    def import_signatures(self, signature_file: str):
        """从文件导入恶意软件签名"""
        try:
            with open(signature_file, 'r') as f:
                signatures = json.load(f)
                count = 0
                for sig, desc in signatures.items():
                    if self.add_malware_signature(sig, desc):
                        count += 1
                logger.info(f"成功导入 {count} 个恶意软件签名")
                return count
        except Exception as e:
            logger.error(f"导入签名文件失败: {str(e)}")
            return 0

    def export_signatures(self, output_file: str):
        """导出恶意软件签名到文件"""
        try:
            with open(output_file, 'w') as f:
                json.dump(self.malware_signatures, f, indent=2)
            logger.info(f"导出 {len(self.malware_signatures)} 个恶意软件签名到 {output_file}")
            return True
        except Exception as e:
            logger.error(f"导出签名失败: {str(e)}")
            return False

    def get_scan_history(self, limit: int = 10):
        """获取扫描历史"""
        try:
            conn = sqlite3.connect(self.scan_history_db)
            c = conn.cursor()
            c.execute("SELECT * FROM scan_history ORDER BY scan_time DESC LIMIT ?", (limit,))
            history = []
            for row in c.fetchall():
                history.append({
                    'id': row[0],
                    'file_path': row[1],
                    'file_hash': row[2],
                    'file_size': row[3],
                    'file_type': row[4],
                    'scan_time': row[5],
                    'is_malware': bool(row[6]),
                    'is_tampered': bool(row[7]),
                    'is_crack': bool(row[8]),
                    'risk_score': row[9],
                    'details': json.loads(row[10]) if row[10] else {}
                })
            conn.close()
            return history
        except Exception as e:
            logger.error(f"获取扫描历史失败: {str(e)}")
            return []


# 使用示例
if __name__ == "__main__":
    print("=" * 60)
    print(f"SecureScan Pro v2.0 - 本地安全扫描工具")
    print(f"作者: SamWu (samwulqy@gmail.com)")
    print(f"发布日期: 2025-09-28")
    print("=" * 60)
    
    scanner = SecureScanPro()
    
    # 扫描单个文件
    test_file = "测试文件.exe"
    print(f"\n扫描文件: {test_file}")
    result = scanner.scan_file(test_file)
    print(json.dumps(result, indent=2, ensure_ascii=False))
    
    # 添加恶意软件签名
    print("\n添加恶意软件签名...")
    scanner.add_malware_signature("new_malware_signature", "新型恶意软件")
    
    # 查看扫描历史
    print("\n最近扫描记录:")
    history = scanner.get_scan_history(3)
    for item in history:
        print(f"[{item['scan_time']}] {item['file_path']} - 风险分数: {item['risk_score']:.2f}")
    
    # 扫描目录
    # print("\n扫描目录...")
    # results = scanner.scan_directory("下载目录")
    # print(f"扫描完成，共扫描 {len(results)} 个文件")
    
    print("\n扫描完成!")


""""
# 初始化扫描器
scanner = SecureScanPro()

# 扫描单个文件
result = scanner.scan_file("下载的文件.exe")

# 扫描整个目录
results = scanner.scan_directory("下载文件夹")

# 添加恶意软件签名
scanner.add_malware_signature("签名哈希", "恶意软件描述")

# 获取扫描历史
history = scanner.get_scan_history(10)
""""
